const app = getApp()
var upload = require('../../../utils/upload');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isAndroid: true,
    checked: false,
    showThemes:false,
    vipauth:false,
    onDate:false,
    onSelector:false,
    themes_name:'',
    minDate: new Date().getTime(),
    maxDate: new Date(2030,1,1).getTime(),
    currentDate: new Date().getTime(),
    cate_id: 0,
    store_id: 0,
    themes:[],
    top_money: 0,
    top_day: 0,
    tempFilePaths: [],
    fileList: [],
    tpl:[],
    top:[]
  },
  //监听页面加载
  onLoad: function (options) {
    app.getParam(options,(param)=>{
      this.setData({
        store_id:param.store_id ? param.store_id : 0,
        isAndroid:app.globalData.isAndroid
      });
      this.getThemes();
      this.getTpl();
      this.getConfig();
    })
  },
  //监听页面显示
  onShow: function () {
    app.loginState();
  },
  //获取栏目
  getThemes: function() {
    app.api().Get('api/v1/ais/infosend/getThemes',(result)=>{
      this.setData({
        themes: result.data
      });
    })
  },
  getTpl: function() {
    app.api().Get('api/v1/ais/infosend/getTpl',{id:this.data.cate_id},(result)=>{
      this.setData({
        tpl: result.data
      });
    })
  },
  //读取配置
  getConfig: function() {
    app.api().Get('api/v1/ais/info/getConfig',(result) =>{
      if (result.code == 200) {
        this.setData({
          top: result.data,
        })
      }
    })
  },
   /**
   * 发表信息
   */
  onSubmit: function (e) {
    var data = e.detail.value;
    if (app.util().isNull(data.content)) {
      app.wxAlert('内容不能为空');
      return;
    }else{
        wx.showLoading({title:'违规内容检测',mask: true})
        this.doMsgSecCheck(data.content,(res)=>{
          wx.hideLoading();
          if(res){
            app.wxAlert('内容中有违规词语,请更换');
          }else{  //无关键字
            if(app.util().isNull(data.telphone)){
              app.wxAlert('联系手机号必须输入');
              return;
            }else{
              if (!(/^1(2|3|4|5|6|7|8|9)\d{9}$/.test(data.telphone))){
                app.wxAlert('请输入正确的手机号');
                return;
              }
            }
            //上传图片
            wx.showLoading({title:'信息发布中',mask: true})
            upload.Upfiles('api/v1/ais/config/upimg',this.data.tempFilePaths,(file) => {
              app.api().Post('api/v1/ais/infosend/send',{
                content: data.content,
                telphone: data.telphone,
                topday: this.data.top_day,
                cate_id: this.data.cate_id,
                store_id: this.data.store_id,
                is_get: this.data.checked ? 1 : 0,
                price: app.util().isNull(data.price) ? 0 : data.price,
                fields: JSON.stringify(this.fields(data)),
                imgs:JSON.stringify(file.filePaths)
              },(rel) => {
                wx.hideLoading();
                if (rel.code == 200) {
                  app.doWechatPay(rel.data,()=>{
                    app.wxAlert(rel.msg,()=>{
                      wx.navigateBack();
                    })
                  }, function () {
                    app.wxAlert('未付款,以普通信息发布.',()=>{
                      wx.navigateBack();
                    })
                  });
                }else{
                  app.wxAlert(rel.msg,()=>{
                    wx.navigateBack();
                  })
                }
              })
            })
         }
      });
    }
  },
  //上传选择图片
  afterRead:function(event){
    wx.showLoading({title:'违规图片检测中',mask: true})
    wx.getFileSystemManager().readFile({
      filePath:event.detail.file[0].path,
      encoding:"base64",
      success:res => {
        this.doImgSecCheck(res.data,rel => {
          wx.hideLoading()
          if(rel){
            app.wxAlert('违规!请更换图片');
            return;
          }else{
            //图片如果正常执行这里
            const { file } = event.detail;
            var fileList = this.data.fileList;
            var tempFilePaths = this.data.tempFilePaths;
            for (let i in file) {
              fileList.push(file[i]);
              tempFilePaths.push(file[i].path);
            }
            this.setData({
              fileList: fileList,
            });
            this.data.tempFilePaths = tempFilePaths;
          }
        })
      }
    })
  },
  //删除图片
  deleteItem: function (res) {
    var tempFilePaths = this.data.tempFilePaths;
    var fileList = this.data.fileList;
    var index = res.target.id;
    if (index > -1) {
      fileList.splice(index,1);
      tempFilePaths.splice(index, 1);
    }
    this.setData({
      fileList:fileList
    })
    this.data.tempFilePaths = tempFilePaths;
  },
  //选择置顶
  selectTop: function (e) {
    var dataset = e.currentTarget.dataset;
    var day = 0;
    if(this.data.top_day != dataset.day){
      day = parseInt(dataset.day);
    }
    this.data.top_money = parseInt(dataset.money);
    this.setData({
      top_day:day
    })
  },
  //动态表单数据
  fields:function (values) {
    var fields = this.data.tpl.fields;
    var field = new Array();
    for (let i in fields) {
      if(app.util().isNull(values[i])){
        var value = {title:fields[i].title,value:''}
      }else{
        var value = {title:fields[i].title,value:values[i]}
      }
      field.push(value)
    }
    return field;
  },
  onChange: function (e) {
    if(e.detail && !this.data.checked){
      app.api().Post('api/v1/ais/Infosend/vipAuth',(result) =>{
        if(result.data.vip){
          this.setData({
            checked: !this.data.checked
          });
        }else{
          this.onClickHide();
        }
      })
    }else{
      this.setData({
        checked: !this.data.checked
      });
    }
  },
  //隐藏遮罩
  onClickHide(e) {
    this.setData({
      vipauth: !this.data.vipauth
    });
  },
  //去认证
  onVipauth(e) {
    this.onClickHide();
    wx.navigateTo({
      url: 'edit',
    })
  },
  //保存表单值
  onIpunt: function (e) {
    var key = e.currentTarget.dataset.id;
    var tpl = this.data.tpl;
        tpl.fields[key].value = e.detail;
  },
  //时间选择器
  selectDate: function (e) {
    this.setData({
      onDate:!this.data.onDate
    });
    if(this.data.onDate){
      this.data.field_key = e.currentTarget.dataset.id;
    }
  },
  onDateConfirm: function (event) {
    var nowdate = app.util().dateFormat(event.detail,'Y/M/D h:m')
    var key = this.data.field_key;
    var tpl = this.data.tpl;
        tpl.fields[key].value = nowdate; 
    this.setData({
      tpl:tpl
    });
    this.selectDate();
  },
  //菜单选择器
  selector: function (e) {
    this.setData({
      onSelector: !this.data.onSelector
    });
    if(this.data.onSelector){
      this.data.field_key = e.currentTarget.dataset.id;
      this.setData({
        columns:this.data.tpl.fields[this.data.field_key].values
      })
    }
  },
  onSelector: function (event) {
    var tpl = this.data.tpl;
        tpl.fields[this.data.field_key].value = event.detail.value; 
    this.setData({
      tpl:tpl
    })
    this.selector();
  },
  //选择主题内容
  onThemes: function () {
    this.setData({
      showThemes:!this.data.showThemes
    })
  },
  //选择主题
  selectThemes: function (e) {
    this.data.cate_id = e.detail.id;
    this.setData({
      themes_name:e.detail.name
    })
    this.getTpl();
    this.onThemes();
  },
  //文字内容安全
  doMsgSecCheck: function (text,callback) {
    wx.serviceMarket.invokeService({
      service: 'wxee446d7507c68b11',
      api: 'msgSecCheck',
      data: {
        "Action": "TextApproval",
        "Text":text
      },
    }).then(res => {
      if(res.errMsg == 'invokeService:ok'){
        if(res.data.Response.EvilTokens.length > 0){
          callback(true)
        }else{
          callback(false)
        }
      }
    })
  },
  //图片安全过滤
  doImgSecCheck:function (image,callback) {
    wx.serviceMarket.invokeService({
      service: 'wxee446d7507c68b11',
      api: 'imgSecCheck',
      data: {
        "Action": "ImageModeration",
        "Scenes": ["PORN", "POLITICS", "TERRORISM"],
        "ImageBase64":image,
      },
    }).then(res => {
      if(res.errMsg == 'invokeService:ok'){
        if(res.data.Response.Suggestion == 'PASS'){
          callback(false)
        }else{
          callback(true)
        }
      }
    })
  },
})